package com.ljw.springsecurity.configuration;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljw.springsecurity.dao.UserRepository;
import com.ljw.springsecurity.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

/**
 * @author liujw
 * @create 2020/4/25 20:30
 */
@Component("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        System.out.println("登录用户名；" + login);
        // 1. 查询用户
        User userFromDatabase = userRepository.findOneByLogin(login);
        ObjectMapper mapper = new ObjectMapper();
        try {
            System.out.println("用户信息；" + mapper.writeValueAsString(userFromDatabase));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (userFromDatabase == null) {
            //log.warn("User: {} not found", login);
            throw new UsernameNotFoundException("User " + login + " was not found in db");
            //这里找不到必须抛异常
        }
        // 2. 设置角色
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (!StringUtils.isEmpty(userFromDatabase.getRole())) {
            Arrays.stream(userFromDatabase.getRole().trim().split(","))
                    .map(s -> s.trim()).filter(s -> !StringUtils.isEmpty(s))
                    .forEach(s -> grantedAuthorities.add(new SimpleGrantedAuthority(s)));
        }
        return new org.springframework.security.core.userdetails.User(login,
                userFromDatabase.getPassword(), grantedAuthorities);
    }
}
